package com.ty.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ty.auto.TokenProperties;
import com.ty.bean.UserInfo;
import com.ty.context.UserContext;

import java.util.*;

public class TokenTemplate {

    TokenProperties properties;//存储配置信息 密钥 有效期...

    public TokenTemplate(TokenProperties tokenProperties) {
        this.properties = tokenProperties;
    }

    /**
     * 生成token
     *
     * @param payload
     * @return
     */
    public String generateToken(Map payload) {
        String token = JWT.create()
                .withHeader(getHeader()) //头部
                .withPayload(payload)
                .withIssuer("by")
                .withExpiresAt(getExpireDate())
                .sign(Algorithm.HMAC256(properties.getSecret()));
        return token;
    }

    /**
     * 验证token
     *
     * @param token
     * @return 1 token无效  2 token过期  3 token有效
     */
    public ValidResult valid(String token) {
        //验证token
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(properties.getSecret()))
                .build();
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = verifier.verify(token);
        } catch (JWTDecodeException e) {
            return ValidResult.INVALID;
        } catch (TokenExpiredException e) {
            return ValidResult.EXPIRE;
        }
        Map<String, Claim> payload = decodedJWT.getClaims();
        int id = payload.get("id").asInt();
        String username = payload.get("username").asString();
        int type = payload.get("type").asInt();
        Claim claim = payload.get("roles");
        String role = claim.toString();
        String[] gdt = role.split("\"");
        UserInfo userInfo = new UserInfo(id, username, gdt[1], type);
        UserContext.set(userInfo);
        return ValidResult.VALID;
    }

    Date getExpireDate() {
        //获取30分钟后日期
        Date date = new Date(System.currentTimeMillis() + properties.getValidTime());
        return date;
    }


    Map getHeader() {
        Map<String, String> map = new HashMap<>();
        map.put("typ", "JWT");
        map.put("alg", "HMAC256");
        return map;
    }
}
